<?php

namespace App\Http\Resources\Article;

use App\Http\Resources\BaseResource;
use App\Models\Article\ArticleCategoryMappingsModel;
use App\Models\Article\ArticleModel;
use App\Models\Article\ArticleUserRelationModel;
use App\Service\Article\ArticleService;
use Illuminate\Http\Resources\MissingValue;

class ApiArticleListResource extends BaseResource
{
    public function toArray($request): array
    {
        return [
            "id"                  => $this->id,
            "type"                => $this->type,
            "title"               => $this->title,
            "previewUrl"          => json_decode($this->previewUrl, true),
            "coverImgUrl"         => $this->coverImgUrl,
            "description"         => $this->description,
            "supportNum"          => $this->supportNum,
            "collectNum"          => $this->collectNum,
            "forwardNum"          => $this->forwardNum,
            "readNum"             => $this->readNum,
            "showNum"             => $this->showNum,
            "content"             => ArticleService::replaceTranscodingContent(
                $this->content,
                $this->transcodingVideoDetail
            ),
            "formatEffectiveTime" => formatDate($this->effectiveTime),
            "effectiveTime"       => $this->effectiveTime,
            "status"              => $this->status,
            "statusText"          => translateEnumCodeToCn(ArticleModel::STATUS_TEXT, $this->status, "-"),
            "publishType"         => $this->publishType,
            "publishTypeText"     => translateEnumCodeToCn(ArticleModel::PUBLISH_TYPE_TEXT, $this->publishType, "-"),
            "createTime"          => $this->createdAt->timestamp,
            "formatCreateTime"    => formatDate($this->createdAt->timestamp, "-"),
            "createUsername"      => $this->whenLoaded(
                "createUserRel",
                function () {
                    return attributeGet($this, "createUserRel.nickname", "-");
                },
                new MissingValue()
            ),
            "sort"                => $this->sort,
            "putTop"              => $this->putTop,
            "putHotTop"           => $this->putHotTop,
            "isCollect"           => $this->whenLoaded(
                "articleUserRelationRel",
                function () {
                    return (bool)$this->articleUserRelationRel->where("articleId", $this->id)
                                                              ->where("type",
                                                                  ArticleUserRelationModel::TYPE_COLLECT)
                                                              ->where("status",
                                                                  ArticleUserRelationModel::STATUS_SUCCESS)
                                                              ->isNotEmpty();
                },
                false
            ),
            "isSupport"           => $this->whenLoaded(
                "articleUserRelationRel",
                function () {
                    return (bool)$this->articleUserRelationRel->where("articleId", $this->id)
                                                              ->where("type",
                                                                  ArticleUserRelationModel::TYPE_LIKE)
                                                              ->where("status",
                                                                  ArticleUserRelationModel::STATUS_SUCCESS)
                                                              ->isNotEmpty();
                },
                false
            ),
            "shareUrl"            => config('open-shop.m') . "content/detail/" . $this->id,
            "extra"               => $this->extra,
            "categoryDetail"      => $this->whenLoaded("articleCategoryMappingsRel", function () {
                return $this->getCategoryDetail();
            }, new MissingValue())
        ]; // TODO: Change the autogenerated stub
    }

    /**
     * @return array
     */
    public function getCategoryDetail(): array
    {
        $categoryDetail = [];
        if ($this->articleCategoryMappingsRel) {
            $this->articleCategoryMappingsRel->each(function (
                ArticleCategoryMappingsModel $articleCategoryMappingsModel
            ) use (&$categoryDetail) {
                if ($articleCategoryMappingsModel->articleCategoryRel->articleCategoryMappingsRelCount >= 2) {
                    $categoryArticleIds = $articleCategoryMappingsModel->articleCategoryRel
                        ->articleCategoryMappingsRel
                        ->pluck("articleId")
                        ->toArray();
                    $articleList        = ArticleModel::query()
                                                      ->with([
                                                          "articleUserRelationRel" => function ($query) {
                                                              $query->where("createdByUid", request()->user()->id)
                                                                    ->whereIn("type", [
                                                                        ArticleUserRelationModel::TYPE_LIKE,
                                                                        ArticleUserRelationModel::TYPE_COLLECT
                                                                    ])
                                                                    ->where("status",
                                                                        ArticleUserRelationModel::STATUS_SUCCESS);
                                                          }
                                                      ])
                                                      ->whereIn("id", $categoryArticleIds)
                                                      ->limit(2)
                                                      ->get();
                    if ($articleList->count() == 2) {
                        $articleCategoryMappingsModel->articleCategoryRel->offsetUnset("articleCategoryMappingsRel");
                        $articleCategoryMappingsModel->articleCategoryRel->article = self::collection($articleList);
                        array_push($categoryDetail,
                            array_merge($articleCategoryMappingsModel->articleCategoryRel->toArray(), [
                                "updatedAtText" => date("Y-m-d H:i:s",
                                    $articleCategoryMappingsModel->articleCategoryRel->updatedAt),
                                "createdAtText" => date("Y-m-d H:i:s",
                                    $articleCategoryMappingsModel->articleCategoryRel->createdAt)
                            ]));
                    }
                }
            });
        }

        array_multisort(
            array_column($categoryDetail, "sort"),
            SORT_ASC,
            array_column($categoryDetail, "updatedAt"),
            SORT_DESC,
            $categoryDetail
        );
        return $categoryDetail;
    }
}
